/*
 * Created on Oct 23, 2008
 */
package com.bjypc.youth.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author huangwei
 * 
 * Calculate the 32bit hex string of a file(or byte stream) Hashing has lots of
 * kinds. Here default is MD5(SHA1, SHA-256, SHA-384, SHA-512 is also supported)
 */
public class ComputeHash {

	private static String hashType = "MD5";

	public static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7',
			'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public static String getHash(InputStream ins) {
		byte[] buffer = new byte[1024];
		String md5String = null;
		MessageDigest md5;
		try {
			md5 = MessageDigest.getInstance(hashType);
			int numRead = 0;
			while ((numRead = ins.read(buffer)) > 0) {
				md5.update(buffer, 0, numRead);
			}
			md5String = toHexString(md5.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ins != null)
				try {
					ins.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}

		return md5String;
	}

	public static String getHash(File file) {
		String md5 = null;
		try {
			InputStream ins;
			ins = new FileInputStream(file);
			md5 = getHash(ins);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return md5;
	}

	public static String toHexString(byte[] b) {
		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
			sb.append(hexChar[b[i] & 0x0f]);
		}
		return sb.toString();
	}
}
